package com.baomidou.ant.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.ant.config.AlipayConfig;
import com.baomidou.ant.entity.Alipay;
import com.baomidou.ant.entity.RealName;
import com.baomidou.ant.entity.User;
import com.baomidou.ant.mapper.AlipayMapper;
import com.baomidou.ant.service.IAlipayService;
import com.baomidou.ant.service.IRealNameService;
import com.baomidou.ant.service.IUserService;
import com.baomidou.ant.utils.IdCardUtils;
import com.baomidou.ant.vo.Response.ResponseMyAlipayVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public  class AlipayServiceImpl extends ServiceImpl<AlipayMapper,Alipay> implements IAlipayService {
    @Autowired
    private IUserService userService;
    @Autowired
    private IRealNameService realNameService;


    @Override
    public String aliPay(HttpServletResponse response, HttpServletRequest request,Integer amount,String orderNumber) throws IOException {
        //response.setContentType("text/html;charset=utf-8");
        //PrintWriter out = response.getWriter();
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest aliPayRequest = new AlipayTradePagePayRequest();
        aliPayRequest.setReturnUrl(AlipayConfig.return_url);
        aliPayRequest.setNotifyUrl(AlipayConfig.notify_url);
        //商户订单号，后台可以写一个工具类生成一个订单号，必填
        //orderNumber
        //String order_number = new String(UUID.randomUUID().toString().replace("-",""));
        //付款金额，从前台获取，必填
        String total_amount =String.valueOf(amount);
        //订单名称，必填
        String subject = new String("答个爽钻石");
        aliPayRequest.setBizContent("{\"out_trade_no\":\"" + orderNumber + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String result = null;
        try {
            result = alipayClient.pageExecute(aliPayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //输出
        // out.println(result);
        log.info("返回结果={}",result);
        return result;
    }

    @Override
    public List<ResponseMyAlipayVo> listMyAlipay(Integer userId) {
        QueryWrapper<Alipay> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<Alipay> alipayList=list(queryWrapper);
        List<ResponseMyAlipayVo> voList=new ArrayList<>();
        for(Alipay alipay:alipayList){
            ResponseMyAlipayVo vo=new ResponseMyAlipayVo();
            BeanUtils.copyProperties(alipay,vo);
            User user=userService.getById(alipay.getUserId());
            vo.setUserName(user.getUsername());
            if(Objects.equals(alipay.getStatus(), "1")){
                vo.setStatus("支付成功");
            }else
                vo.setStatus("支付失败");
            voList.add(vo);
        }
        return voList;
    }

    @Override
    public boolean checkRealName(Integer userId) {
        QueryWrapper<RealName> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        RealName realName=realNameService.getOne(queryWrapper);
        //判断年龄或是否完成实名认证
        if(realName==null|| IdCardUtils.age(realName.getIdCard())<=18){
            return false;
        }else
            return true;
    }

    @Override
    public Integer payNums(Integer userId,Integer amount) {
        QueryWrapper<Alipay> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("pay_amount",amount);
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("status","1");
        List<Alipay> alipayList=list(queryWrapper);
        return alipayList.size();
    }
}
